# spatial auto-logistic regression. implemented from slrm in 
# spatstat package by adding an neighbor term in covraites.
#
# data.ppp: a point pattern
# formula: a normal R formular, like ~x+y
# covariates: a list of covariables
# 
# rstep: 1 means + closest neighbor. 2 mean both + and × neighbor (not totally correct)
# Author: Guochun Shen
# Data:   2011-12-20
# Project:spatial statistic
# Email:  shenguochun@gmail.com
###############################################################################

auto_logistic=function(data.ppp,formula=NULL,covariates=NULL,link="logit",rstep=1,dimyx=NULL){
	#find the number of neighbors
	if(is.null(dimyx))
		dimyx=covariates[[1]]$dim
	if(is.null(formula)){
		formula=auto_formu(names(covariates))
	}
	binary=as.logical(quadratcount(data.ppp,ny=dimyx[1],nx=dimyx[2]))
	xy=get_xy(1:length(binary),dimyx)[binary,]
	nneibxy=unlist(lapply(dnearneigh(xy,0,rstep),function(x) length(x[x!=0])))
	binary[binary]=nneibxy
	dim(binary)=dimyx
	neib.im=im(binary,xcol=covariates[[1]]$xcol,yrow=covariates[[1]]$yrow)
	covariates[[length(covariates)+1]]=neib.im
	names(covariates)[length(covariates)]="neib"
    formula=as.formula(paste("data.ppp ~",as.character(formula)[-1],"+ neib"))
	re=slrm(formula,data=covariates)
	re=step(re,trace=0)
	return(re)
}

nobs.slrm=function (object, ...) 
{
	npoints(object$Data$response)
}
